package me.zhengjie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.qiniu.util.Json;
import lombok.RequiredArgsConstructor;
import me.zhengjie.domain.AliMessageData;
import me.zhengjie.domain.AliMessageLog;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.service.AliMessageLogService;
import me.zhengjie.service.AliMessageService;
import me.zhengjie.utils.AliMessageEnum;
import me.zhengjie.utils.MessageUtil;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AliMessageServiceImpl  implements AliMessageService {


   private final AliMessageLogService aliMessageLogService;


    @Override
    public void sendMessage(String phone, AliMessageEnum messageEnum, String params) {

    }

    @Override
    public void sendCode(String phone, String code) {
        JSONObject object = new JSONObject();
        object.put("code",code);
        CommonResponse commonResponse = null;
        try {
            commonResponse = MessageUtil.sendSimpleMessage(phone, AliMessageEnum.TEST_MESSAGE, object.toJSONString());
        } catch (ClientException e) {
            AliMessageLog log = new AliMessageLog();
            log.setCode(code);
            log.setPhone(phone);
            log.setMessage(e.getErrMsg());
            aliMessageLogService.create(log);
            throw new BadRequestException(e.getErrMsg());
        }
        if (commonResponse == null){
            throw new BadRequestException("短信发送失败");
        }
        String responseData = commonResponse.getData();
        AliMessageData data = Json.decode(responseData, AliMessageData.class);

        AliMessageLog log = new AliMessageLog();
        log.setCode(code);
        log.setConent(object.toJSONString());
        log.setBizId(data.getBizId());
        log.setMessage(data.getMessage());
        log.setRequestId(data.getRequestId());
        log.setPhone(phone);
        aliMessageLogService.create(log);
        if (!data.getMessage().equals("OK")){
            throw new BadRequestException(data.getMessage());
        }

    }
}
